home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 15746 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: lrz-muenchen.de!news
  2. From: watzka@stat.uni-muenchen.de (Kurt Watzka)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to access memory allocated in function
  5. Date: 21 Apr 1996 15:55:09 GMT
  6. Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
  7. Distribution: world
  8. Message-ID: <4ldlot$9uv@sparcserver.lrz-muenchen.de>
  9. References: <4ddbe3$so3@josie.abo.fi> <slrn4nkrsq.bv6.shadows@whateva.kuwait.net>
  10. NNTP-Posting-Host: sun2.lrz-muenchen.de
  11.  
  12. shadows@whateva.kuwait.net (The ShadowS Know) writes:
  13.  
  14. >In article <4ddbe3$so3@josie.abo.fi>, Christoffer Sundqvist wrote:
  15. >>How can i access memory allocated dynamically in a function after i leave the 
  16. >>function, something like this:
  17. >>
  18. >>void sub(int *p)
  19. >>{
  20. >> p = malloc(.....);
  21. >>}
  22. >>
  23.  
  24. >p = (int *)malloc(sizeof(int));
  25. >What we've done is cast it as an pointer to an integer then allocated it
  26. >the size of one int (thus it points to a space in memory that has the size
  27. >of holding 1 integer). Ofcourse anything might be in that memory address
  28. >you'd need to place something there to clear it up. 
  29.  
  30. As a solution to the original posters problem, this is entirely useless,
  31. but it is not completely useless, since it can still be used as a bad
  32. example :-).
  33.  
  34. The problem that pointers are passed by value like all other variables in
  35. C is treated in the FAQ for comp.lang.c in the question named
  36. "I have a function which accepts, and is supposed to initialize, a pointer"
  37. using somewhat archaic syntax. For those of us who cannot decipher 
  38. K&R C, Steve Summit describes:
  39.  
  40.    void f(int *ip)
  41.    {
  42.       satic int dummy = 5;
  43.       ip = &dummy;
  44.    }
  45.  
  46. Casting the return value of malloc() is not a useful tip for standard
  47. C, but it may be needed for older implementations. An implementation
  48. that accepts "void sub(int *p)" but declares malloc() as returning 
  49. something other than a "void *" in <stdlib.h> might be a rare 
  50. collectors item.
  51.  
  52. Kurt
  53. --
  54. | Kurt Watzka                             Phone : +49-89-2180-6254
  55. | watzka@stat.uni-muenchen.de
  56.  
  57.  
  58.